/**
 * 
 */
package com.cqan.account.controller;

import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.cqan.account.entity.Role;
import com.cqan.account.entity.User;
import com.cqan.account.service.RoleService;
import com.cqan.account.service.UserService;
import com.cqan.controller.BaseController;
import com.cqan.exception.AppException;
import com.cqan.orm.PropertyFilter;
import com.cqan.orm.PropertyFilter.MatchType;
import com.cqan.util.encode.EncodeUtils;
import com.google.common.collect.Lists;

import static com.cqan.common.ViewName.*;

/**
 * @Description 用户管理CONTROLLER
 * @author slaton.wu@gmail.com
 * @date 2012-6-29下午7:29:54
 *
 */
@Controller
@RequestMapping("/account")
public class UserController extends BaseController<User>{

	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="roleService")
	private RoleService roleService;
	
	@RequestMapping(value="/login.htm",method=RequestMethod.GET)
	public ModelAndView login()throws AppException{
		
		return new ModelAndView(LOGIN);
	}
	
	/**
	 * 用户管理列表
	 * @param pageNo
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list.htm")
	public ModelAndView list(Integer pageNo,HttpServletRequest request)throws AppException{
		ModelAndView mav = new ModelAndView(USER_LIST);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page.setPageNo(pageNo);
		page.setOrder("desc");
		page.setOrderBy("createTime");
		page = userService.search(page, filters);
		mav.addObject("page", page);
		return mav;
	}
	
	@RequestMapping(value="/pwd.htm")
	public ModelAndView pwd()throws AppException{
		return  new ModelAndView(USER_PWD);
	}
	@RequestMapping(value="/modify.htm",method=RequestMethod.POST)
	public ModelAndView modify(HttpServletRequest req,Long id)throws AppException{
		try {
			User u = userService.get(id);
			User user = getRequestEntity(req);
			if (u!=null) {
					this.copyProperties(u, user);
					String [] rids = req.getParameterValues("rids");
					List<Role> roles = Lists.newArrayList();
					if (rids!=null&&rids.length>0) {
						for (String rid : rids) {
							if (rid!=null) {
								roles.add(roleService.get(Long.parseLong(rid)));
							}
						}
					}
					u.setRoles(roles);
					u.setLastLoginTime(Calendar.getInstance().getTime());
					u.setLastLoginIp(req.getRemoteAddr());
					userService.update(u);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException();
		} 
		
		return   new ModelAndView(new RedirectView("list.htm?pageNo="+req.getParameter("pageNo")));
	}
	
	@ResponseBody
	@RequestMapping(value="/delete.htm",method=RequestMethod.POST)
	public String delete(String ids)throws AppException{
		try {
			User user = getUserDetails();
			if (ids!=null) {
				StringTokenizer st = new StringTokenizer(ids,"-");
				List<Long> list = Lists.newArrayList();
				while (st.hasMoreTokens()) {
					String id = st.nextToken();
					if (id!=null&&!"".equals(id)) {
						list.add(Long.parseLong(id));
					}
				}
				if (list.contains(user.getId())) {
					return "不能删除自己！";
				}
				userService.delete(list);
				return "删除成功！";
			}
		} catch (Exception e) {
			throw new AppException();
		}
		return  "删除失败！";
	}
	
	@RequestMapping(value="/edit.htm",method=RequestMethod.GET)
	public ModelAndView edit(Long id,int pageNo)throws AppException{
		ModelAndView mav = new ModelAndView(USER_EDIT);
		User user = userService.get(id);
		List<Role> roles = roleService.findBy("enabled", true, MatchType.EQ);
		mav.addObject("user", user);
		mav.addObject("pageNo", pageNo);
		mav.addObject("roles", roles);
		return mav;
	}
	
	@RequestMapping(value="/modifyPwd.htm",method=RequestMethod.POST)
	public ModelAndView modifyPwd(String newpwd)throws AppException{
		User user = getUserDetails();
		if (user!=null) {
			user.setPassword(EncodeUtils.md5(user.getUsername(), newpwd));
			userService.update(user);
		}
		ModelAndView mv = new ModelAndView(SUCCESS);
		return mv;
	}
	
	@ResponseBody
	@RequestMapping(value="/checkPwd.htm")
	public boolean  checkPwd(String pwd)throws AppException{	
		User user = getUserDetails();
		if (user!=null) {
			if(!(EncodeUtils.md5(user.getUsername(), pwd)).equals(user.getPassword())){
				return false;
			}
			return true;
		}
			return true;
	}
}
